import { MatchData, OptionData, TableRow } from './type';
import { WebSiteWithCategory } from '@/types/website';
import { JobStep } from './Step';
import ConditionTable from './Match/conditionTable';
import OptionTable, { Row } from './Option/table';

export const useRemove = (step: Ref<JobStep>) => {
  /**
   * the effect of remove website
   * @param website
   */
  const removeWebSite = (website: WebSiteWithCategory) => {
    const conditionData = step.value.getStep('CONDITION_RELATION')
      ?.data as MatchData;
    if (conditionData) {
      const tableCollection = new ConditionTable(conditionData);
      const removeList: TableRow[] = [];
      tableCollection.tableData.forEach(item => {
        if (compare(website, item.website, ['category_code', 'website_code'])) {
          removeList.push(item);
        }
      });
      removeList.forEach(item => {
        tableCollection.remove(item);
        removeCondition(item);
      });
    }
  };

  const removeCondition = (condition: TableRow) => {
    const optionData = step.value.getStep('OPTION_RELATION')
      ?.data as OptionData;
    if (optionData) {
      const idx = optionData.conditions.findIndex(
        item => condition.alias_name == (item.alias_name || item.condition_name)
      );
      if (idx > -1) {
        const option = optionData.conditions[idx];
        if (option) {
          const tableCollection = new OptionTable(option);
          const removeList: Row[] = [];
          tableCollection.tableData.forEach(item => {
            if (
              compare(item, condition.website, [
                'website_code',
                'category_name',
                'condition_name',
              ])
            ) {
              removeList.push(item);
            }
          });
          removeList.forEach(item => {
            tableCollection.removeRow(item);
          });
          if (!option.options.length) {
            optionData.conditions.splice(idx, 1);
          }
        }
      }
    }
  };

  return { removeWebSite, removeCondition };
};
